<template>
  <div>
    <div class="tab">
      <van-tabs v-model:active="new_type" swipeable sticky :offset-top="50">
        <van-tab
          v-for="item in new_types"
          :title="item"
          :name="item"
          :key="item"
        >
          <NewList :loadMore="loadMore" :news="news" />
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, computed, watch } from "vue";
import { Notify, Toast } from "vant";
import NewList from "@/components/news/index.vue";
import { useStore } from "vuex";
import { BoomService } from "@/api/booms";
export default {
  name: "UserNews",
  components: { NewList },
  setup() {
    const store = useStore();
    const loadMore = () => {
      if (data.newTotal === data.news.length) {
        Toast("已全部加载");
        return;
      }
      data.page += 1;
    };

    let data = reactive({
      search_key: computed(() => store.state.Search.search_key),
      news: [],
      page: 1,
      new_type: "",
      loadMore: loadMore,
      newTotal: 0,
      new_types: [
        "全部",
        "军事",
        "娱乐",
        "国际",
        "国内",
        "财经",
        "体育",
        "互联网",
        "科技",
        "游戏",
        "汽车",
        "房产",
      ],
    });
    const listnews = (is_search = false) => {
      BoomService.news({
        page: data.page,
        search_key: data.search_key,
        new_type: data.new_type,
      }).then((res) => {
        if (res.data.code == 0) {
          if (is_search) {
            data.news = res.data.data.news;
          } else {
            // @ts-ignore
            data.news = [...data.news, ...res.data.data.news];
          }
          data.newTotal = res.data.data.total;
        } else {
          Notify({ type: "danger", message: res.data.message });
        }
      });
    };
    listnews();
    watch(
      () => data.page,
      (newValue, oldVlaue) => {
        listnews();
      }
    );
    watch(
      () => data.search_key,
      (newValue, oldVlaue) => {
        listnews(true);
      }
    );
    watch(
      () => data.new_type,
      (newValue, oldVlaue) => {
        listnews(true);
      }
    );
    return {
      ...toRefs(data),
    };
  },
};
</script>

<style lang="less">
.tab {
  margin-bottom: 80px;
}
</style>